package com.visitor.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.visitor.bean.Admin;
import com.visitor.mapper.AdminMapper;
import com.visitor.utils.DateUtils;
import com.visitor.web.vm.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class AdminService {
	@Resource
	private AdminMapper adminMapper;

	@Transactional
	public Response<String> saveOrUpdate(Admin user) {
			if(user.getId()!=null) {
				Admin isExtis=adminMapper.isExtis(user);
				if(null!=isExtis){
					return Response.error(300);//账号已经存在
				}else{
					adminMapper.updateByPrimaryKey(user);
				}
			}else {
				Admin search=new Admin();
				search.setAccount(user.getAccount());
				search=adminMapper.selectByParam(search);
				if(null!=search){
					return Response.error(300);//账号已经存在
				}else{
					user.setCreateTime(DateUtils.getTime());
					adminMapper.insert(user);
				}
			}
			return Response.ok();
	}
	
	public Admin findUserById(Long id) {
		Admin user = adminMapper.selectByPrimaryKey(id);
		return user;
	}
	
	public int deleteUserById(Long id) {
		return adminMapper.deleteByPrimaryKey(id);
	}
	
	public PageInfo<Admin> getAllByPage(int pageNum,int pageSize,Admin admin){
		PageHelper.startPage(pageNum, pageSize, true);
		List<Admin> list= adminMapper.selectAll(admin);
		if(list==null||list.isEmpty()) {
			list = new ArrayList<>();
		}
		return new PageInfo<>(list);
	}
	public Admin login(Admin admin){
		return adminMapper.selectByParam(admin);

	}
}
